package encaps.action;

import encaps.entities.Grant;
import encaps.entities.Role;
import encaps.entities.UserLocal;
import encaps.entities.UserLocalHome;
import encaps.logging.JMSUtil;
import encaps.logging.Log;
import encaps.resources.Config;
import encaps.resources.Image;
import encaps.resources.Labels;
import encaps.resources.Response;
import encaps.utils.*;
import java.util.Date;
import javax.ejb.CreateException;
import javax.ejb.FinderException;
import javax.naming.NamingException;
import org.jdom.Element;

public class RegistrationAction extends ShowRegistrationPageAction {

    public static final String REGISTER = "registration";

    public RegistrationAction(ActionContext context, Grant requiredGrant) {
        super(context, requiredGrant);
    }

    @Override
    public Element execute() throws ActionExecutionException {
        try {
            Element dataToReEnter = validateParameters();
            if (dataToReEnter != null) {
                return dataToReEnter;
            }

            String login = actionContext.getTextParameter(LOGIN);
            String password = actionContext.getTextParameter(PASSWORD);
            String role = Role.USER;
            String info = actionContext.getTextParameter(INFO);
            String email = actionContext.getTextParameter(EMAIL);
            String contacts = actionContext.getTextParameter(CONTACTS);

            UserLocalHome userHome = EntityUtil.getUserHome();
            UserLocal user = userHome.create(login, null, info, contacts, password, email, role);

            String picName = String.format("%d-%s", user.getID(), login);
            String picPath = IOHelper.uploadFile(actionContext, PICTURE, picName, Config.getUserImagesDirectory());
            if (picPath != null) {
                user.setAvatar(picPath);
            }

            actionContext.setUserLogin(login);
            actionContext.setUserRole(role);

            JMSUtil.sendLogMessage(Log.REGISTRATION, user.getID(),
                    user.getLogin(), new Date(), null, null, null);

            return XMLHelper.createTextMessage(Labels.getLabel(Labels.PROFILE_REGISTERED_SUCCESSFULLY));

        } catch (CreateException ex) {
            throw new ActionExecutionException(Labels.getLabel(Labels.CANNOT_EXECUTE_ACTION), ex);
        } catch (SystemException ex) {
            throw new ActionExecutionException(Labels.getLabel(Labels.CANNOT_EXECUTE_ACTION), ex);
        } catch (NamingException ex) {
            throw new ActionExecutionException(Labels.getLabel(Labels.CANNOT_EXECUTE_ACTION), ex);
        }
    }

    private Element validateParameters() throws SystemException {
        String login = actionContext.getTextParameter(LOGIN);
        String loginMessage = null;
        if (StringUtil.isEmpty(login)) {
            loginMessage = Labels.getLabel(Labels.ENTER_LOGIN_MESSAGE);
        }
        try {
            EntityUtil.getUserHome().findByLogin(login);
            loginMessage = Labels.getLabel(Labels.USER_ALREADY_EXISTS);
        } catch (FinderException ex) {
            //если пользователь не найден - все хорошо
        } catch (NamingException ex) {
            throw new SystemException(Labels.getLabel(Labels.CANNOT_EXECUTE_ACTION), ex);
        }

        String password = actionContext.getTextParameter(PASSWORD);
        String rePassword = actionContext.getTextParameter(PASSWORD_REPEAT);
        String passMessage = null;
        String rePassMessage = null;
        if (StringUtil.isEmpty(password)) {
            passMessage = Labels.getLabel(Labels.ENTER_PASSWORD_MESSAGE);
        }
        if (!password.equals(rePassword)) {
            rePassMessage = Labels.getLabel(Labels.PASSWORDS_MISMATCH_MESSAGE);
        }
        if (loginMessage == null && passMessage == null && rePassMessage == null) {
            return null;
        }

        Element response = XMLHelper.createElement(Response.RESPONSE);
        Element e = XMLHelper.addChild(response, Response.ENTITY);
        e.setAttribute(Response.EDIT, "true");

        XMLHelper.addChild(e, XMLHelper.createHeader(Labels.getLabel(Labels.REGISTRATION)));
        XMLHelper.addChild(e, XMLHelper.createImage("", PICTURE));
        XMLHelper.addChild(e, XMLHelper.createTextField(Labels.getLabel(Labels.LOGIN), actionContext.getTextParameter(LOGIN), LOGIN, loginMessage));
        XMLHelper.addChild(e, XMLHelper.createPasswordField(Labels.getLabel(Labels.PASSWORD), PASSWORD, passMessage));
        XMLHelper.addChild(e, XMLHelper.createPasswordField(Labels.getLabel(Labels.REPEAT_PASSWORD), PASSWORD_REPEAT, rePassMessage));
        XMLHelper.addChild(e, XMLHelper.createTextArea(Labels.getLabel(Labels.INFO), actionContext.getTextParameter(INFO), INFO));
        XMLHelper.addChild(e, XMLHelper.createTextField(Labels.getLabel(Labels.EMAIL), actionContext.getTextParameter(EMAIL), EMAIL));
        XMLHelper.addChild(e, XMLHelper.createTextField(Labels.getLabel(Labels.CONTACTS), actionContext.getTextParameter(CONTACTS), CONTACTS));

        XMLHelper.addChild(e, XMLHelper.createImageButton(Image.getImage(Image.REGISTRATION), RegistrationAction.REGISTER));

        return response;
    }
}
